#include "Mystdio.h"
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<stdlib.h>
#include<unistd.h>
_FILE*_fopen(const char* filename,const char* flag)
{
   int f = 0;   
   int fd = -1;
   if(strcmp(flag,"w") == 0)
   {
     f = (O_CREAT|O_WRONLY|O_TRUNC);
     fd = open(filename,f,0666);
   }
   else if(strcmp(flag,"a") == 0)
   {
     f = (O_CREAT|O_WRONLY|O_APPEND);
     fd = open(filename,f,0666); 
   } 
   else if(strcmp(flag,"r") == 0)
   {
     f = (O_RDONLY);
     fd = open(filename,f);
   }
   else return NULL;  
   if(fd == -1) {
     return NULL;
   } 

   _FILE* fp = (_FILE*)malloc(sizeof(_FILE));
   if(fp == NULL) return NULL;
   fp->_fileno = fd;
   fp->flag = FLUSH_LINE;
   fp->out_pos = 0;
     
   return fp;
}


int _fwrite(const void *ptr,size_t size,int n,_FILE* fp)
{
  //先不考虑n  
    memcpy(&fp->outbuff[fp->out_pos],ptr,size);
    fp->out_pos += size;
    if(fp->flag & FLUSH_NOW)
    {
      write(fp->_fileno,fp->outbuff,fp->out_pos);
      fp->out_pos = 0;
    }
    else if((fp->flag & FLUSH_LINE ))
    {
      //abcd\n'\0'
      //abcd'\n'daaaa
      if(fp->outbuff[fp->out_pos - 1] == '\n')
      {
       write(fp->_fileno,fp->outbuff,fp->out_pos);
       fp->out_pos = 0;
      }
      else{
        return size;
      }
    }
    else if(fp->flag & FLUSH_ALL)
    {
      if(fp->out_pos == SIZE)
      {
      write(fp->_fileno,fp->outbuff,fp->out_pos);
      fp->out_pos = 0;
      }
      else{
        return size;
      }
    }
    
    return size;
}
void _fflush(_FILE* fp)
{
 if(fp->out_pos > 0)
 {
    write(fp->_fileno,fp->outbuff,fp->out_pos);
  fp->out_pos = 0;
 }
}
void _fclose(_FILE* fp)
{
  if(fp == NULL) return;
  _fflush(fp);
  close(fp->_fileno);
  free(fp);
}

 // const char* str = "hello fwrite\n";
